<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>打开小程序</title>
    <script src="/sticsale/html/common/weixin-js-sdk-1.6.0.js" type="text/javascript"></script>
</head>
<script>
    function getQueryVariable(variable) {
        var query = window.location.search.substring(1)
        var vars = query.split('&')
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=')
            if (pair[0] === variable) {
                return decodeURIComponent(pair[1])
            }
        }
        return false
    }

    const baseUrl = 'https://cs.libao.cn'
    const appId = getQueryVariable('appid') || 'wxb278686d357bc342'
    // https://open.ins10.cn/couponApi/openapi/wx/miniApp/${appid}/public/login
    const maShortAddressApi = `${baseUrl}/customer/wechat-customer/wx/miniApp/${appId}/shortAddress`


    /**
     * 格式化参数
     * @param data
     * @return {string}
     */
    function formatParams(data, isPer = true) {
        var arr = []
        for (var name_1 in data) {
            // encodeURIComponent() ：用于对 URI 中的某一部分进行编码
            arr.push(encodeURIComponent(name_1) + '=' + encodeURIComponent(data[name_1]))
        }
        // 添加一个随机数参数，防止缓存
        // arr.push('v=' + random())

        var url = arr.join('&')
        return isPer ? '?' + url : url
    }

    /**
     * 网络请求
     * @type {{get(*, *=): *}}
     */
    var HttpUtil = function (url, params, method) {
        if (params === void 0) {
            params = {}
        }
        if (method === void 0) {
            method = 'POST'
        }
        return new Promise(function (resolve, reject) {
            var xhr = null
            if (window.XMLHttpRequest) {
                xhr = new XMLHttpRequest()
            } else { // IE6及其以下版本
                xhr = new ActiveXObjcet('Microsoft.XMLHTTP')
            }
            // 监听事件，只要 readyState 的值变化，就会调用 readystatechange 事件
            xhr.onreadystatechange = function () {
                // readyState属性表示请求/响应过程的当前活动阶段，4为完成，已经接收到全部响应数据
                if (xhr.readyState === 4) {
                    var status_1 = xhr.status
                    if (status_1 >= 200 && status_1 < 300) { // status：响应的HTTP状态码，以2开头的都是成功
                        var response = xhr.responseText
                        if (response) {
                            resolve(response)
                        } else {
                            reject(response)
                        }
                    } else {
                        reject('网络错误')
                    }
                }
            }
            //GET请求 把参数放到url
            if (method.toLocaleUpperCase() === 'GET') {
                url += formatParams(params)
            }
            xhr.open(method.toLocaleUpperCase(), url, true) // 最后一个参数改为false为同步请求
            //必须，设置提交时的内容类型
            xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
            // 传输数据
            xhr.send(JSON.stringify(params))
        })
    }

    /**
     * 有值 并且30天内 返回jumpUrl 否则返回空
     * @return {null|*}
     */
    function checkCache() {
        var data = localStorage.getItem(getCacheKey())
        if (!data) {
            return null
        }
        var json = JSON.parse(data)
        var now = parseInt(new Date().getTime() / 1000)

        //过期清空
        if (!json.expireTime || Number(json.expireTime) < now) {
            localStorage.removeItem(getCacheKey())
            return null
        }
        return json.jumpUrl
    }

    function setCache(jumpUrl, expireTime) {
        var data = {
            jumpUrl,
            expireTime,
        }
        localStorage.setItem(getCacheKey(), JSON.stringify(data))
    }

    function getCacheKey() {
        return 'CS_MA_LINK_' + window.location.href
    }

    function goUrl(url) {
        window.location.replace(url)
    }


    function checkMa() {
        // js中如下判断
        var ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            wx.miniProgram.getEnv((res) => {
                if (res.miniprogram) {
                    var path = getQueryVariable('path') || ''
                    var query = getQueryVariable('query') || ''
                    if (!query) {
                        query = ''
                    } else if (query.indexOf("?") !== 0) {
                        query = "?" + query
                    }
                    wx.miniProgram.navigateTo({
                        url: path + query
                    })
                } else {
                    //不是微信小程序
                    browserFun()
                }
            })
        } else {
            //不是微信浏览器
            browserFun()
        }
    }

    function browserFun() {
        var url = checkCache()
        if (url) {
            goUrl(url)
            return
        }
        var path = getQueryVariable('path') || ''
        var query = getQueryVariable('query') || ''

        const day_30 = 30 * 24 * 60 * 60
        const expireTime = parseInt(new Date().getTime() / 1000) + day_30
        HttpUtil(maShortAddressApi,
            {path: path, query: query, expireTime: expireTime}, 'GET').then(function (jumpUrl) {
            if (jumpUrl.indexOf('https://') === 0) {
                setCache(jumpUrl, expireTime)
                goUrl(jumpUrl)
            }
        }, function (error) {
            alert(error)
        })
    }

    //检查是否小程序 小程序走原生打开  其他走短链打开
    function mounted() {
        checkMa()
    }

    mounted()


</script>
<body>
</body>
</html>
